package com.auto.learning.activity;

import java.util.ArrayList;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.auto.learning.MainActivity;
import com.auto.learning.R;
import com.auto.learning.bean.BookBean;
import com.auto.learning.net.Cache;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.service.MusicPlayManager;
import com.auto.learning.view.MyProgressDialog;
import com.auto.learning.view.SharedPreferencesUtils;
import com.baidu.mobstat.StatService;

/**
 * Activity基础类
 *
 * @author wangjian 
 *
 */
@SuppressLint("ClickableViewAccessibility")
public class BaseActivity extends FragmentActivity {

	protected ScrollView scrollview;
	protected LinearLayout contentLayout;
	protected PtrClassicFrameLayout ptrFrame;
	protected LinearLayout backBtn;
	protected TextView tv;
	protected LinearLayout baseMore;
	protected ImageView rightMore;
	protected MyProgressDialog progressDialog;
	protected LinearLayout netErrHint;
	protected Button retryBtn;
	protected InputMethodManager imm;
	protected LinearLayout activity_base_title;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpRequestHelper.GET_LOCAL_BOOKBEAN_SUCCESS:
				final BookBean bean = (BookBean) msg.obj;
				if (bean != null) {
					handler.postDelayed(new Runnable() {
						public void run() {
							ArrayList<BookBean> m_list = new ArrayList<BookBean>();
							m_list.add(bean);
							MusicPlayManager.getInstance(BaseActivity.this).setPlayList(m_list).setBookId(bean.getBookId()).setContinuePlayPause(true).play();
						}
					}, 1500);
					Intent intent = new Intent(BaseActivity.this, PlayActivity.class);
					intent.putExtra("bookId", bean.getBookId());
					intent.putExtra("faceImg", TextUtils.isEmpty(bean.getFaceImg()) ? "" : bean.getFaceImg());
					intent.putExtra("canRead",bean.getCanRead());
					intent.putExtra("needBuy",bean.getNeedBuy());
					startActivity(intent);
				}
				break;
			}
		};
	};
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		super.setContentView(R.layout.activity_base);
		activity_base_title=(LinearLayout) findViewById(R.id.activity_base_title);
		activity_base_title.setBackgroundColor(getResources().getColor(R.color.black));
		backBtn = (LinearLayout) findViewById(R.id.activity_base_back);
		scrollview = (ScrollView) findViewById(R.id.activity_base_scrollview);
		scrollview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				IBinder ib = null;
				try {
					ib = getCurrentFocus().getWindowToken();
				} catch (Exception e) {
					return false;
				}
				if (ib != null) {
					return imm.hideSoftInputFromWindow(ib, 0);
				} else {
					return false;
				}

			}

		});
		contentLayout = (LinearLayout) findViewById(R.id.activity_base_content);
		tv = (TextView) findViewById(R.id.activity_base_titlename);
		baseMore = (LinearLayout) findViewById(R.id.activity_base_more);
		rightMore = (ImageView) findViewById(R.id.main_image_play);
		rightMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				StatService.onEvent(BaseActivity.this, "LogEventTypePlayViewButtonClic", "右上角的显示播放页面按钮");
				MusicPlayManager manager = MusicPlayManager.getInstance(BaseActivity.this);
				if (manager.getPlayList() != null && manager.getPlayList().size() > 0) {
					Intent intent = new Intent(BaseActivity.this, PlayActivity.class);
					intent.putExtra("bookId", manager.isPlayingBookId()[0]);
					intent.putExtra("faceImg", manager.getFaceImage());
					intent.putExtra("canRead",manager.getCanRead());
					int needBuy=1;
					//传递是否免费书籍判断
					for (int i = 0; i < manager.getPlayList().size(); i++) {
							if(manager.isPlayingBookId()[0]==manager.getPlayList().get(i).getBookId()){
								needBuy=manager.getPlayList().get(i).getNeedBuy();
							}
					}
					intent.putExtra("needBuy", needBuy);
					startActivity(intent);
				} else {
					boolean con = (boolean) SharedPreferencesUtils.getParam(BaseActivity.this,HttpRequestHelper.CONTINUE_PLAY_BEFORE, true);
					if (con) {
						int bId = (int) SharedPreferencesUtils.getParam(BaseActivity.this,HttpRequestHelper.CONTINUE_PLAY_BOOKID, 0);
						if (bId != 0) {
							Cache.getBookBeanById(BaseActivity.this,bId, handler);
						}
					}
			}}
		});
		
		if (MusicPlayManager.getInstance(this).isPlaying()) {
			animPlaying();
		}else {
			animPlayed();
		}
		netErrHint = (LinearLayout) findViewById(R.id.ac_base_neterrhint);
		retryBtn = (Button) findViewById(R.id.ac_base_retry);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		progressDialog = MyProgressDialog.createLoadingDialog(this);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseActivity.this.finish();
			}
		});
	}
	
	@Override
	protected void onResume() {
		if (MusicPlayManager.getInstance(this).isPlaying()) {
			animPlaying();
		}else {
			animPlayed();
		}
		super.onResume();
	}
	
	public void animPlaying(){
		rightMore.setBackgroundResource(R.anim.play_stute);
		AnimationDrawable _animaition = (AnimationDrawable)rightMore.getBackground();
		_animaition.setOneShot(false);   
		_animaition.start();
	}
	
	
	public void animPlayed(){
		rightMore.setBackgroundResource(R.drawable.now2);
	}
	
	public void hideTitle(){
		activity_base_title.setVisibility(View.GONE);
	}
	
	public void hideRight(){
		rightMore.setVisibility(View.GONE);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			System.out.println("down");
			if (this.getCurrentFocus() != null) {
				if (this.getCurrentFocus().getWindowToken() != null) {
					imm.hideSoftInputFromWindow(this.getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 在scrollview里装载内容
	 */
	@Override
	public void setContentView(int layoutResID) {
		contentLayout.setVisibility(View.GONE);
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		inflater.inflate(layoutResID, scrollview);
	}

	/**
	 * 当内容为listview或者webview这类可滑动的view时，在linearlayout里装载防止与scrollview滑动冲突
	 *
	 * @param layoutResID
	 */
	public void setViewInLine(int layoutResID) {
		scrollview.setVisibility(View.GONE);
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		inflater.inflate(layoutResID, contentLayout);
	}

	/**
	 * 设置返回键是否可见
	 */
	public void setBackBtn(boolean flag) {
		if (flag) {
			backBtn.setVisibility(View.VISIBLE);
		} else {
			backBtn.setVisibility(View.GONE);
		}
	}

	
	/**
	 * 设置标题名称
	 */
	@Override
	public void setTitle(int resid) {
		tv.setText(resid);
	}

	public void setTitle(String title) {
		tv.setText(title);
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (progressDialog != null) {
			progressDialog.cancel();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	
	
	
}
